// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri(str) {
	var o = parseUri.options,
		m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
	q: {
		name: "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

(function ($) {
	var //method to wire up buttons via jquery ui in a certain context
		wireButtons = function(context) {
			$('.button-remove-colitem', context).click(function() {
				$(this).parents('div[data-colitem]').eq(0).hide('slow', function() { $(this).remove(); });
			});

			$('.button-add-colitem', context).click(function() {
				var button = $(this);
                button.hide();
                a1.throbber(button.parent(), function(remove) {
				    $.ajax({
				      url: '/SiteManagement/NewAlternate',
				      success: function(data, status, xhr) {
					    var newItem = $(data);
					    steve.wireNewContent(newItem);
					    //set data-colitem
                        remove();
                        button.show();
					    button.before(newItem);
				      },
				      dataType: 'html'
				    });
                });

			});

            $('.add-button', context).button({
                icons: { primary: 'ui-icon-plus' },
				text: false
            }).tooltip();

            $('.external-link-button', context).button({
                icons: { primary: 'ui-icon-extlink' },
				text: false
            }).tooltip();

            $('.delete-button', context).button({
                icons: { primary: 'ui-icon-trash' },
				text: false
            }).tooltip();

			$('.new-document-button', context).button({
				icons: { primary: 'ui-icon-document' },
				text: false
			}).tooltip();

			$('.search-button', context).button({
				icons: { primary: 'ui-icon-search' },
				text: false
			}).tooltip();

			$('.edit-button', context).button({
				icons: { primary: 'ui-icon-pencil' },
				text: false
			}).tooltip();

            $(':button:submit', context).button({icons:{primary: 'ui-icon-disk'}, text: false}).tooltip();

			$(':button,a.button', context).not(':submit').button();
			
			$('.buttonset', context).buttonset();
			$('.toolbar', context).addClass('ui-widget-header ui-corner-all');
		},
		steve = window.steve = {
			wireNewContent: function(context) {
				var split = function(val) {
			        return val.split(/,\s*/);
		        }, extractLast = function (term) {
			        return split(term).pop();
		        };

                wireButtons(context);

                $('.category-list', context).autocomplete({
                    source: function(request, response) {
                        $.getJSON('/Category/GetCategories', { term: extractLast(request.term) }, response);
                    },
                    search: function() {
                        //custom minLength
                        var term = extractLast(this.value);
                        if(term.length < 2) {
                            return false;
                        }
                    },
                    focus: function() {
                        //prevent value inserted on focus
                        return false;
                    },
                    select: function(event, ui) {
                        var terms = split(this.value);
                        //remove the current input
                        terms.pop();
                        //add the selected item
                        terms.push(ui.item.value);
                        //add placeholder to get the comma-and-space at the end
                        terms.push('');
                        this.value = terms.join(', ');
                        return false;
                    }                        
                });
			}  
		};

	$(document).ready(function(){
		//wire up form submits to fix the collection editor indexes before submitting
		$('form:has([data-collection])', '#bd').submit(function() {
			$(this).find('[data-collection]').each(function() {
				var newPrefix = $(this).attr('data-collection');
				$(this).find('>[data-colitem]').each(function(index) {
					var newName = newPrefix + '[' + index + ']';
					var oldName = $(this).attr('data-colitem');

					$(this).find(':input[name]').each(function() {
						var thisItem = $(this);
						thisItem.attr('name',  thisItem.attr('name').replace(oldName, newName));
					});

					$(this).find('label[for]').each(function() {
						var thisItem = $(this);
						thisItem.attr('for',  thisItem.attr('for').replace(oldName, newName));
					});
				});
			});
		});

		steve.wireNewContent('#bd');

		//wire up forms for collection index fix

		//wire up datetime picker, this is an extension, should be replaced when jquery UI supports time
		$('.input-datetime', '#bd').datetimepicker({
			ampm: true
		});

		//setup tooltip if this jquery ui version supports it
		if($.fn.tooltip) {
            $('a[title],input[title],span[title]', '#bd').tooltip();
        }

		//hack for nullable date pickers
		var nullableDatepickers = $('.input-datetime.nullable', '#bd');

		if(nullableDatepickers.length > 0) {
			nullableDatepickers.each(function(index, element) {
				var thisItem = $(this)
					, button = $('<button type="button">Null Date</button>');
					
				button.insertAfter(thisItem);
				button.button({
					text: false,
					icons: { primary: 'ui-icon-cancel' }
				}).click(function() {
					thisItem.val('');
				});
			});
		}

        $('div.accordion', '#bd').accordion({
            autoHeight: false,
        });

        var dialog = $('#revision-dialog', '#bd');

        if(dialog.length > 0) {
            var form = dialog.parents('form:first');
            form.submit(function() {
                if(!dialog.data('revisionData')) {
                    dialog.dialog({
                        modal: true,
                        buttons: { 'Ok': function() { dialog.dialog('close'); dialog.data('revisionData', true); form.submit(); } }
                    }).parent().appendTo(form);
                    return false;
                }
            });
        }
	});
})(jQuery);